$(function () {

    layui.use(['layer', 'form', 'element'], function () {

        var layer = layui.layer,
            form = layui.form(),
            element = layui.element();

        $("#date_begin").datetimepicker({
            format: 'yyyy-mm-dd', //显示格式
            todayHighlight: 1, //今天高亮
            language: 'zh-CN', //日期
            minView: "month", //设置只显示到月份
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            autoclose: 1 //选择后自动关闭
        });

        $("#date_end").datetimepicker({
            language: 'zh-CN', //日期
            format: 'yyyy-mm-dd', //显示格式
            todayHighlight: 1, //今天高亮
            minView: "month", //设置只显示到月份
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            autoclose: 1 //选择后自动关闭
        });

        //点击确定 按时间段赛选
        $('.time-btn').click(function () {

            var date_begin = $('#date_begin').val();
            var date_end = $('#date_end').val();

            var stringTime1 = date_begin,
                stringTime2 = date_end;

            var timestamp1 = Date.parse(new Date(stringTime1));
            timestamp1 = timestamp1 / 1000;
            var timestamp2 = Date.parse(new Date(stringTime2));
            timestamp2 = timestamp2 / 1000;

            if (timestamp1 > timestamp2) {
                layer.msg('开始时间不能大于结束时间', { time: 2000, icon: 2 });
                return false;
            }

            if (isNaN(timestamp1)) {
                layer.msg('开始时间不能为空', { time: 2000, icon: 2 });
                return false;
            }
            if (isNaN(timestamp2)) {
                layer.msg('' + '结束时间不能为空', { time: 2000, icon: 2 });
                return false;
            }

            var timeArr = new Object();

            timeArr.date_begin = stringTime1;
            timeArr.date_end = stringTime2;

            $.ajax({

                url: '/Summary/searchTime',
                data: timeArr,
                type: 'post',
                dataType: 'json',

                success: function success(response) {
                    var arr = Object.keys(response);
                    //console.log( response );
                    var _content = '';
                    for (var i in response) {
                        for (var j in response[i]) {
                            _content += '<div class="list-box"><div class="list-title"><a href="javascript:;" class="close-open-a">' + i + '年第' + j + '周 ( ' + getDateRange(i, j) + ' ) <i class="icon-ii icon-double-angle-right"></i></a></div>' + '<div class="list-content"><table class="table table-bordered table-hover" style="table-layout: fixed;">' + '<colgroup><col width="200"><col width="150"><col width="150"><col><col></colgroup>' + '<thead><tr><th>部门</th><th>姓名</th><th>状态</th><th>标题</th><th>发布时间</th></tr></thead>' + '<tbody>';
                            for (var k in response[i][j]) {
                                //console.log(response[i][j][k]);
                                _content += '<tr>' + '<td>' + response[i][j][k]["deparname"] + '</td>' + '<td><a href="/Summary/subordinate/id/' + response[i][j][k]["id"] + '" target="_blank">' + response[i][j][k]["nickname"] + '</a></td>' + '';
                                if (response[i][j][k]["workSummary"] != false) {
                                    _content += '<td><span class="tag tag-success">已提交</span></td>' + '<td><a href="/Summary/detail?id=' + response[i][j][k]["workSummary"]["id"] + '" target="_blank">' + response[i][j][k]["workSummary"]["title"] + '</a></td>' + '<td>' + timestampToTime(response[i][j][k]["workSummary"]["create_time"]) + '</td>';
                                } else {
                                    _content += '<td><span class="tag tag-danger">未提交</span></td><td></td><td></td>';
                                }
                                _content += '</tr>';
                            }

                            _content += '</tbody></table></div></div>';
                        }
                    }
                    $('.search-item').html(_content);

                    $('.search-item .list-box:last-child').find('.list-content').addClass('weekAction');
                    $('.search-item .list-box:last-child').find(' i').removeClass('icon-double-angle-right');
                    $('.search-item .list-box:last-child').find(' i').addClass('icon-double-angle-down');
                }

            });
        });

        //获取对象length
        function length(o) {
            var count = 0;
            for (var i in o) {
                count++;
            }
            return count;
        };

        function getXDate(year, weeks, weekDay) {
            var date = new Date(year, "0", "1");
            var time = date.getTime();
            time += (weeks - 1) * 7 * 24 * 3600000;
            date.setTime(time);
            return getNextDate(date, weekDay);
        }

        function getNextDate(nowDate, weekDay) {
            // 0是星期日,1是星期一,...
            weekDay %= 7;
            var day = nowDate.getDay();
            var time = nowDate.getTime();
            var sub = weekDay - day;
            if (sub <= 0) {
                sub += 0;
            }
            time += sub * 24 * 3600000;
            nowDate.setTime(time);
            return nowDate;
        }

        function getNowFormatDate(theDate) {
            var day = theDate;
            var Year = 0;
            var Month = 0;
            var Day = 0;
            var CurrentDate = "";
            // 初始化时间
            Year = day.getFullYear(); // ie火狐下都可以
            Month = day.getMonth() + 1;
            Day = day.getDate();
            CurrentDate += '';
            if (Month >= 10) {
                CurrentDate += Month + "月";
            } else {
                CurrentDate += "" + Month + "月";
            }
            if (Day >= 10) {
                CurrentDate += Day + '日';
            } else {
                CurrentDate += "" + Day + '日';
            }
            return CurrentDate;
        }

        // 获取日期范围显示
        function getDateRange(_year, _week) {
            var beginDate;
            var endDate;
            if (_year == null || _year == '' || _week == null || _week == '') {
                return "";
            }
            beginDate = getXDate(_year, _week, 1);
            endDate = getXDate(_year, _week - 0 + 1, 7);
            return getNowFormatDate(beginDate) + " 至 " + getNowFormatDate(endDate);
        }

        // 点击展开关闭周数据
        $('.search-item').on('click', '.close-open-a', function () {
            if ($(this).find(' i').hasClass('icon-double-angle-down')) {

                $(this).find(' i').removeClass('icon-double-angle-down');
                $(this).find(' i').addClass('icon-double-angle-right');
                $(this).parent().next().removeClass('weekAction');
            } else {

                $('.list-content').removeClass('weekAction');
                $('.icon-ii').removeClass('icon-double-angle-down');
                $('.icon-ii').addClass('icon-double-angle-right');
                $(this).find(' i').removeClass('icon-double-angle-right');
                $(this).find(' i').addClass('icon-double-angle-down');
                $(this).parent().next().addClass('weekAction');
            }
        });

        function timestampToTime(timestamp) {
            var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            //D = date.getDate() + ' ';
            var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate() + 1) : date.getDate() + 1) + ' ';
            //h = date.getHours() + ':';
            var h = (date.getHours() + 1 < 10 ? '0' + (date.getHours() + 1) : date.getHours() + 1) + ':';
            //m = date.getMinutes() + ':';
            var m = (date.getMinutes() + 1 < 10 ? '0' + (date.getMinutes() + 1) : date.getMinutes() + 1) + ':';
            //s = date.getSeconds();
            var s = date.getSeconds() + 1 < 10 ? '0' + (date.getSeconds() + 1) : date.getSeconds() + 1;
            return Y + M + D + h + m + s;
        }

        form.on('select', function (data) {
            // console.log(data.value); //得到被选中的值
            localStorage.setItem('value', data.value);
            location.href = ThinkPHP['AJAX'] + '/Summary/subordinate/id/' + data.value;
        });

        // var html = JSON.parse(uertData);
        // console.log(html);
        // // 获取对象子元素长度
        // var _len = Object.getOwnPropertyNames(html).length - 1;
        //
        //
        // if(_len > 0){
        //     var _html = '';
        //     // 拼装dialog数据
        //     for (var i = 0; i < _len; i++) {
        //         _html += '<div class="box-user" style="margin:  0 0 10px 0;">' +
        //             '<p class="depart-p" style="background: #e2e2e2;font-weight: 700;font-size: 15px;text-indent: 1em;border-left: 5px solid #bbb;">' + html[i]['name'] + '</p> <div class="user-list">';
        //         for (var j = 0; j < Object.getOwnPropertyNames(html[i]['users']).length - 1; j++) {
        //             _html += '<span class="user-span" title="' + html[i]['users'][j]['nickname'] + '" uid="' + html[i]['users'][j]['id'] + '" style="height: 30px;width:65px;text-align:center;border-radius: 2px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;display: inline-block;padding: 4px 10px;margin: 10px 5px 0 0;">' + html[i]['users'][j]['nickname'] + '</span>';
        //         }
        //         _html += '</div></div>';
        //     }
        // }else{
        //    var _html = '<p style="padding: 120px 0;text-align: center;font-size: 20px;color: #999;">没有数据</p>';
        // }

        // 点击选中
        $(document).on('click', '.user-span', function () {
            $('.layui-layer-dialog .user-span').removeClass('active-span');
            $(this).addClass('active-span');
        });

        $('.subordinate-user').click(function () {
            layer.open({
                type: 1,
                id: 'layerUserSelector',
                title: '选择下属',
                area: ['100%', '100%'],
                scrollbar: false,
                success: function success() {
                    element.init();
                },
                content: $('#subordinates').html()
            });
        });

        // 点击下属名字定位到下属的总结列表
        $(document).on('click', '.user-span', function () {
            // 跳转前打开 loading 层避免重复点击
            var _loading = layer.load(2, {
                shade: [0.5, '#fff']
            });
            // 定位至下属总结列表
            location.href = '/Summary/subordinate/id/' + $(this).attr('uid');
        });

        $('.pName').click(function () {

            $.ajax({
                url: '/Summary/getMySubordinates',
                data: {
                    uid: $(this).attr('uid')
                },
                type: 'GET',
                dataType: 'json',
                success: function success(response) {}

            });
        });
    });
});